import { useState, useEffect, useContext } from 'react';
import { NavBar, Space, List, Dialog, Toast, Popup } from "antd-mobile";
import { AddOutline, MinusOutline, RightOutline } from 'antd-mobile-icons';
import { useHistory, useRouteMatch } from "react-router-dom";

import GroupMemberSelectContactor from '../../../components/GroupMembersSelectContactor';
import ModifyGroupInfo from '../ModifyGroupInfo';
import Collection from '../../../components/Collection';
import AvatarImage from '../../../components/AvatarImage';
import { MySdkStoreContext } from '../../../context';
import { ContentType, CustomDataType } from '../../../constants';

import './style.scss';

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const { params: { cid } } = useRouteMatch();
  const { mockConfig: { userId: myUserId, userName: myUserName } } = mySdkStore;
  const [members, setMembers] = useState([]);
  const [settings, setSettings] = useState({});
  const [conversationDetail, setConversationDetail] = useState({});
  const [modifyInfoProps, setModifyInfoProps] = useState({ visible: false });
  const [collectionCompProps, setCollectCompProps] = useState({ visible: false });
  const [groupMemberSelectContactorProp, setGroupMemberSelectContactorProp] = useState({visible: false, getListApi: '', onOk: () => {}, onClose: () => {}});

  // 查询回话详情
  const queryConversationDetail = async () => {
    const info = await mySdkStore.sdk.querySingleConversation({ cid });
    setConversationDetail(info);
  }

  // 查询群成员
  const getMember = async (pageIndex) => {
    const { rows = [] } = await mySdkStore.sdk.listGroupMembers({ cid, pageIndex, pageSize: 10 });
    // 处理排序，将群组、群管理员排在前排位置
    setMembers(rows.sort((a, b) => {
      const a1 = a.roleId === 1 ? 9999 : a.roleId;
      const b1 = b.roleId === 1 ? 9999 : b.roleId;
      return b1 - a1;
    }));
  }

  // 查询群设置信息
  const querySetting = async () => {
    const { groupSetting } = await mySdkStore.sdk.queryGroupSetting({ cid });
    setSettings(groupSetting);
  }

  useEffect(() => {
    queryConversationDetail();
    getMember(1);
    querySetting();
  }, []);

  // 发送群成员变更通知消息
  const sendSystemMessage = async (changeData) => {
    let content = '';
    const nickNames = changeData.membersList.map(({ nickName, userName }) => userName ?? nickName).join('，');
    if (changeData.type === 'add') {
      content = `${myUserName}邀请 ${nickNames} 加入群聊`;
    } else if (changeData.type === 'remove') {
      content = `${myUserName}将 ${nickNames} 移出群聊`;
    }
    const enc = new TextEncoder();
    const msgBody = {
      msgType: ContentType.Custom,
      msgContent: {
        data: enc.encode(content),
        dataType: CustomDataType.System,
        dataVersion: '0.0.1',
        extInfo: {},
        bizParams: {},
      }
    }
    // await mySdkStore.sdk.setCurrentCid(cid);
    const msgParams = mySdkStore.sdk.messageBuilder(msgBody);
    await mySdkStore.sdk.sendMessage(msgParams);
  }

  // 增加群成员
  const handleAddMember = async (selectedItems, allInfoItems) => {
    try {
      await mySdkStore.sdk.addMemberToGroup({ cid, members: selectedItems });
      setGroupMemberSelectContactorProp({ visible: false});
      getMember(1);
      setConversationDetail({ ...conversationDetail, memberCount: +conversationDetail.memberCount + selectedItems.length});
      sendSystemMessage({ type: 'add', membersList: allInfoItems });
    } catch(e: any) {
      if (e?.errorMessage) {
        Toast.show(e?.errorMessage);
        return;
      }
    }
  }

  // 移除群成员
  const handleRemoveMember = async (selectedItems, allInfoItems) => {
    try {
      await mySdkStore.sdk.removeMemberFromGroup({ cid, members: selectedItems });
      setGroupMemberSelectContactorProp({ visible: false});
      getMember(1);
      setConversationDetail({ ...conversationDetail, memberCount: conversationDetail.memberCount - selectedItems.length});
      sendSystemMessage({ type: 'remove', membersList: allInfoItems });
    } catch(e: any) {
      if (e?.errorMessage) {
        Toast.show(e?.errorMessage);
        return;
      }
    }
  }

  // 处理点击“+”群成员，展示“选择用户”界面
  const handleAddMemberVisible = async () => {
    setGroupMemberSelectContactorProp({
      visible: true,
      title: '添加群成员',
      cid,
      getListApi: 'queryUsers',
      listFilterFunc: (list) => list.filter(item => !members.find(m => m.userId === item.userId)),
      onOk: handleAddMember,
      onClose: () => setGroupMemberSelectContactorProp({ visible: false})
    });
  }

  // 处理点击“-”群成员，展示“选择群成员”界面
  const handleRemoveMemberVisible = () => {
    setGroupMemberSelectContactorProp({
      visible: true,
      title: '移除群成员',
      cid,
      getListApi: 'listGroupMembers',
      onOk: handleRemoveMember,
      onClose: () => setGroupMemberSelectContactorProp({ visible: false})
    });
  }

  // 处理点击">"单条配置信息编辑如编辑“我在群里的昵称”，跳转到统一的编辑页面
  const handleModifyText = ({ key, value, groupUpdateType = 'overall', label = '', updateApi = 'updateGroup', inputType = 'input', rules }: {[key: string]: any}) => {
    setModifyInfoProps({
      visible: true,
      cid,
      modifyKey: key,
      value,
      navTitle: label || '更新群信息',
      updateType: groupUpdateType,
      updateApi,
      inputType,
      rules,
      onClose: (isRefresh) => {
        if (isRefresh) queryConversationDetail();
        setModifyInfoProps({ visible: false });
      }
    });
  }

  // 处理“退出群聊”
  const handleQuitGroupChat = async() => {
    const isConfirm = await Dialog.confirm({
      content: '确定要退出吗？',
    });
    if (!isConfirm) {
      return;
    }
    const { errorMessage } = await mySdkStore.sdk.removeMemberFromGroup({ cid, members: [{ userId: mySdkStore.mockConfig.userId }] });
    if (errorMessage) {
      Toast.show(errorMessage);
      return;
    }
    Toast.show('你已退出群聊');
    history.go(-2);
  }

  // 处理“解散群聊”
  const handleDismissGroupChat = async() => {
    const isConfirm = await Dialog.confirm({
      content: '确定要解散吗？',
    });
    if (!isConfirm) {
      return;
    }
    const { errorMessage } = await mySdkStore.sdk.closeConversation({ cid });
    if (errorMessage) {
      Toast.show(errorMessage);
      return;
    }
    Toast.show('你已解散群聊');
    history.go(-2);
  }

  // “群标签”标记成功回调
  const handleCollectionOk = async (tagCodes, allTagInfos) => {
    try {
      // mySdkStore.sdk.collectSession({ cid, tagCodes });
      const tags = allTagInfos.map(({ name }) => name);
      await mySdkStore.sdk.updateGroup({ cid, updateType: 'tags', group: { tags: tags }});
      Toast.show('标记成功');
      setConversationDetail({ ...conversationDetail, tags });
      setCollectCompProps({ visible: false });
    } catch(e) {
      console.log(e);
    }
  }

  // 处理点击“群标签”，展示“选择标签”界面
  const handleCollect = () => {
    setCollectCompProps({
      visible: true,
      cid,
      onOk: (tagCode, allTagInfos) => handleCollectionOk(tagCode, allTagInfos),
      onClose: () => setCollectCompProps({ visible: false }),
    });
  }

  return (<div className="chatGroupDetailSettingPage">
      <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}>群设置</NavBar>
      <div className="groupIcon">
        <List style={{ '--border-top': 'none' }} >
          <List.Item
            prefix={<AvatarImage
              src={conversationDetail.sessionLogoUrl}
              style={{ borderRadius: 8 }}
              fit='cover'
              width={42}
              height={42}
              groupName={conversationDetail.name}
              preventLink={!settings?.isAllowMemberTalkSecret}
            />}
            description={conversationDetail.remark}
          >
            { conversationDetail.name }
          </List.Item>
        </List>
      </div>
      <div className="groupMemberInfo">
        <Space wrap style={{ '--gap': '25px' }}>
          {
            members.map((item) =>
              <div className="avaterCard" key={item.id}>
                <div className="imageWrap">
                  <AvatarImage
                    src={item.avatarUrl}
                    nickName={item.nickName}
                    userName={item.userName}
                    userId={item.userId}
                    style={{ marginBottom: 8, borderRadius: 8 }} fit='cover' width={42} height={42}
                  />
                  { item.roleId === 1 && <div className="memberRole">群主</div> }
                  { item.roleId === 2 && <div className="memberRole">群管理</div> }
                </div>
                { item.userName || item.nickName }
              </div>
              )
          }
          { (myUserId === conversationDetail.ownerId || (conversationDetail.adminUsers || []).indexOf(myUserId) > -1) &&
            <div className="operatorBtn" onClick={handleAddMemberVisible}>
              <AddOutline />
            </div>
          }
          { (myUserId === conversationDetail.ownerId || (conversationDetail.adminUsers || []).indexOf(myUserId) > -1) &&
            <div className="operatorBtn" onClick={handleRemoveMemberVisible}>
              <MinusOutline />
            </div>
          }
        </Space>
        <div className="checkAllMemberBar" onClick={() => history.push({ pathname: `/groupMember/${cid}` })}>
          查看全部成员（{conversationDetail.memberCount}）<RightOutline />
        </div>
      </div>
      <List style={{ margin: '12px 0' }}>
        <List.Item extra={conversationDetail?.relationVO?.userNick || '未设置'} onClick={() => handleModifyText({ key: 'nickName', value: conversationDetail?.relationVO?.userNick, label: '我在本群的昵称', updateApi: 'updateUserInfoInGroup' })}>
          我在本群的昵称
        </List.Item>
        <List.Item extra={conversationDetail?.relationVO?.userMark || '未设置'} onClick={() => handleModifyText({ key: 'userMark', value: conversationDetail?.relationVO?.userMark, label: '群备注', updateApi: 'updateUserInfoInGroup' })}>
          群备注
        </List.Item>
      </List>
      <List style={{ margin: '12px 0' }}>
        <List.Item extra={conversationDetail.name} onClick={() => handleModifyText({ key: 'name', value: conversationDetail.name, label: '群聊名称', groupUpdateType: 'name', rules: { maxLength: 10 } })}>
          群聊名称
        </List.Item>
        <List.Item extra={conversationDetail.remark || '无'} onClick={() => handleModifyText({ key: 'remark', value: conversationDetail.remark, inputType: 'textArea', groupUpdateType: 'remark', label: '群介绍' })}>
          群介绍
        </List.Item>
        { settings.isAllowNotice &&
        <List.Item extra={conversationDetail.notice || '无'} onClick={() => handleModifyText({ key: 'notice', value: conversationDetail.notice, inputType: 'textArea', groupUpdateType: 'notice', label: '群公告' })}>
          群公告
        </List.Item>
        }
        { !mySdkStore.isHideSomeFunctions &&
        <List.Item extra={(conversationDetail.tags || []).join('、') || '无'} onClick={handleCollect}>
          群标签
        </List.Item>
        }
        { (myUserId === conversationDetail.ownerId || (conversationDetail.adminUsers || []).indexOf(myUserId) > -1) &&
          <List.Item  onClick={() => history.push({ pathname: `/chatGroupPermission/${cid}`})}>
            群管理
          </List.Item>
        }
      </List>
      { myUserId === conversationDetail.ownerId && <div className="buttonBar" onClick={handleDismissGroupChat}>解散群聊</div>}
      { myUserId !== conversationDetail.ownerId && <div className="buttonBar" onClick={handleQuitGroupChat}>退出群聊</div>}

      { groupMemberSelectContactorProp.visible && <GroupMemberSelectContactor {...groupMemberSelectContactorProp} /> }
      { modifyInfoProps.visible && <Popup visible bodyClassName="modifyGroupInfoComponent">
        <ModifyGroupInfo {...modifyInfoProps} />
      </Popup>
      }
      {collectionCompProps.visible &&
      <Popup visible={collectionCompProps.visible} bodyClassName="selectorOperationsBarComponnet-collectionPopup">
        <Collection {...collectionCompProps} />
      </Popup>
      }
    </div>
  )
}